package com.cros.email;

/*
* Fichero: EnviarMail.java
* Autor: Chuidiang
* Fecha: 5/04/07 18:14
*/


import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.AuthenticationFailedException;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.cros.image.Screenshot;
import com.sun.mail.smtp.SMTPSendFailedException;


/**
* Ejemplo de envio de correo simple con JavaMail
*
* @author Chuidiang
*
 */
public class SendMail{
	private static SendMail instance = null;	
	private Session session = null;
	private Transport trans = null;
	
	private Properties properties = null;
	private String pwd;
	private String user;
	private String host;
	
	private SendMail() throws Exception {
		System.out.println("Reading mail.properties ...");
		new RedPropertiesMail("mail.properties");
		System.out.println("mail.properties is Ok!! ...");
		init();
		System.out.println("Inicializa valores OK!!!");
		connect();
		System.out.println("connect Ok!! ...");
	}
	
	public static synchronized SendMail getInstance() throws Exception{
		if(instance == null){
			try{
				instance = new SendMail();
			}catch(Exception e){
				e.printStackTrace();
				throw e;
			}
		}
		return instance;
	}
	
	private void init(){
		properties = new Properties();
		properties.put("mail.smtp.host", RedPropertiesMail.MAIL_SMTP_HOST);
		properties.put("mail.smtp.auth", RedPropertiesMail.MAIL_AUTH);
		properties.put("mail.smtp.port", RedPropertiesMail.MAIL_SMTP_PORT);
		properties.put("mail.smtp.user", RedPropertiesMail.MAIL_SMTP_USER);
		properties.put("mail.smtp.starttls.enable", RedPropertiesMail.MAIL_STARTTLS_ENABLE);

		
		pwd=RedPropertiesMail.MAIL_PWD;
		user=RedPropertiesMail.MAIL_SMTP_USER;
		host=RedPropertiesMail.MAIL_SMTP_HOST;
	}
	
	
	
	public synchronized boolean sendMail(String recipients[], String subject, String message , String from) throws Exception{
		try{
			
			Thread.sleep(RedPropertiesMail.MAIL_TIME_TO_SEND);
			
			
			InternetAddress addressFrom = new InternetAddress(from);	  
			InternetAddress[] addressTo = new InternetAddress[recipients.length];

			for (int i = 0; i < recipients.length; i++){
				addressTo[i] = new InternetAddress(recipients[i]);
			}
			
			//Enviando un mensaje sencillo
			
			Message msg = new MimeMessage(session);
			// Quien envia el correo
			msg.setFrom(addressFrom);
			//Quien recibe el mensaje
			msg.setRecipients(Message.RecipientType.TO, addressTo);
			//Si va a llevar copia oculta
			if(RedPropertiesMail.MAIL_WITH_BBC){
				msg.setRecipient(Message.RecipientType.BCC,new InternetAddress(RedPropertiesMail.MAIL_TO_BBC));
			}
			//Message.RecipientType.TO Destinatario principal del mensaje
			//Message.RecipientType.CC Destinatario al que se env�a copia del mensaje
			//Message.RecipientType.BCC Destinatario al que se env�a copia, pero sin que los dem�s destinatarios puedan verlo.
			msg.setSubject(subject);
			msg.setContent(message, "text/html");
			
			trans.sendMessage(msg,msg.getAllRecipients());  
			
			return true;
			}catch(AddressException addresException){
				connect();
				addresException.printStackTrace();
				
				throw addresException;
				
			}catch(SMTPSendFailedException smtpException){
				if(trans!=null){
					trans.close();
				}
				connect();
				smtpException.printStackTrace();
				throw smtpException;
				
			}catch(MessagingException messaginException){
				if(trans!=null){
					trans.close();
				}
				connect();
				messaginException.printStackTrace();
				throw messaginException;
				
			}catch(Exception exception){
				if(trans!=null){
					trans.close();
				}
				connect();
				exception.printStackTrace();
				throw exception;
		}
	}
	
	
	public synchronized boolean sendMail(String recipients[], String subject, String message , String from,String pathAttached,String fileName) throws Exception{
		try{
			
			Thread.sleep(RedPropertiesMail.MAIL_TIME_TO_SEND);
			
			
			InternetAddress addressFrom = new InternetAddress(from);	  
			InternetAddress[] addressTo = new InternetAddress[recipients.length];

			for (int i = 0; i < recipients.length; i++){
				addressTo[i] = new InternetAddress(recipients[i]);
			}
			
			//Enviando un mensaje con adjuntos
			BodyPart texto = new MimeBodyPart();
            texto.setContent(message, "text/html");
            
            // Se compone el adjunto con la imagen
           BodyPart adjunto = new MimeBodyPart();
           adjunto.setDataHandler(new DataHandler(new FileDataSource(pathAttached)));
           adjunto.setFileName(fileName);

            // Una MultiParte para agrupar texto e imagen.
            MimeMultipart multiParte = new MimeMultipart();
            multiParte.addBodyPart(texto);
            multiParte.addBodyPart(adjunto);
            
            // Se compone el correo, dando to, from, subject y el
            // contenido.
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(addressFrom);
            msg.setRecipients(Message.RecipientType.TO, addressTo);
        	//Si va a llevar copia oculta
			if(RedPropertiesMail.MAIL_WITH_BBC){
				msg.setRecipient(Message.RecipientType.BCC,new InternetAddress(RedPropertiesMail.MAIL_TO_BBC));
			}
            msg.setSubject(subject);
            msg.setContent(multiParte);
			
			
			
			trans.sendMessage(msg,msg.getAllRecipients());  
			
			return true;
			}catch(AddressException addresException){
				connect();
				addresException.printStackTrace();
				
				throw addresException;
				
			}catch(SMTPSendFailedException smtpException){
				if(trans!=null){
					trans.close();
				}
				connect();
				smtpException.printStackTrace();
				throw smtpException;
				
			}catch(MessagingException messaginException){
				if(trans!=null){
					trans.close();
				}
				connect();
				messaginException.printStackTrace();
				throw messaginException;
				
			}catch(Exception exception){
				if(trans!=null){
					trans.close();
				}
				connect();
				exception.printStackTrace();
				throw exception;
		}
	}

	  
	  private void connect()throws Exception{
		  try{
				session = Session.getInstance(properties);	
				session.setDebug(RedPropertiesMail.MAIL_DEBUG);  
				trans = session.getTransport(new InternetAddress(user));
				trans.connect(host,user, pwd);
					
			}catch(AuthenticationFailedException authentication){
				if(trans!=null){
					trans.close();
				}
				authentication.printStackTrace();
				throw authentication;
				
			}catch(MessagingException messaging){
				messaging.printStackTrace();
				throw messaging;
				
			}catch(IllegalStateException ilegal){
				ilegal.printStackTrace();
				throw ilegal;
				
			}catch(Exception ex){
				ex.printStackTrace();
				throw ex;
			}
		 }
	  
	  
public static void main(String argv[]){
	try{
	
	SendMail send = SendMail.getInstance();
	
	String recipients[]={"cros1511@hotmail.com"};
	
	Screenshot s = new Screenshot ();
	s.writeScreenshot();

	String pathFile = s.getPath().concat(s.getFile());
	
	if(send.sendMail(recipients,"the screenshot","The screenshot message", RedPropertiesMail.MAIL_FROM,pathFile,s.getFile())){
		System.out.println("the message was OK");
		s.deleteScreenshot();
	}else{
		System.out.println("the message was Error");
		s.deleteScreenshot();
	}
	
	}catch(Exception ex){
		ex.printStackTrace();
	}
}
	
}